package controller

import (
	"gin-epg/internal/app/common/rsp"
	"gin-epg/internal/app/store"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
)

func File(c *gin.Context) {
	filename, ok := c.Params.Get("filename")
	if !ok {
		rsp.Error(c, "无效的文件名")
		return
	}
	// 去掉 filename 最前面的 /
	filename = filename[1:]

	storeService := store.GlobalStoreService

	fileStream, err := storeService.GetFileStream(filename)
	if err != nil {
		rsp.Error(c, err.Error())
		return
	}

	// 检查 fileStream 是否实现了 io.Closer 接口
	if closer, ok := fileStream.(io.Closer); ok {
		defer closer.Close()
	}

	// 获取文件信息
	fileInfo, err := storeService.GetFileInfo(filename)
	if err != nil {
		rsp.Error(c, err.Error())
		return
	}

	// 使用 http.ServeContent 实现零拷贝
	http.ServeContent(c.Writer, c.Request, filename, fileInfo.ModTime(), fileStream)
}
